package com.Ele_Demo.jackiez;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import com.Ele_Demo.jackiez.util.LogUtil;
import com.Ele_Demo.jackiez.db.DBOpenHelper;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class download extends Activity implements OnClickListener{
	private DBOpenHelper mOpenHelper;
	public static final int DIALOG_UPLOAD_PROGRESS = 0;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 1;
	private ProgressDialog mProgressDialog;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab2);
		((TextView)this.findViewById(R.id.text)).setText("Tab2");
		Button btn_download = (Button)findViewById(R.id.downloadbutton);
        btn_download.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		BeginToDownload();
	}
	
	public void BeginToDownload(){
		starttodownload();
		starttoimport();
		
	}
    public void starttodownload(){
    	try{
    		File dir = new File("/data/data/com.Ele_Demo.jackiez/databases/");
    		dir.mkdir();
    	}
    	catch(Exception e){
			LogUtil.LogShow("[download]", "the folder already been or creating error!", LogUtil.DEBUG);
    	}
    	String url = "http://test.bjcargo.com/MyContacts2011427547.txt";
    	new DownloadFileAsync().execute(url);
    }    
    
    
    public void starttoimport(){
        Button btn_import = (Button)findViewById(R.id.downloadbutton);
		mOpenHelper = new DBOpenHelper(btn_import.getContext());
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        ContentResolver cr = getContentResolver();   
        Importer importer = new Importer();
        importer.ImportContacts(db,cr);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_UPLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Uploading file..");
    //mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    case DIALOG_DOWNLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Downloading file..");
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    default:
    return null;
    }
    }
	
	//The downloading Asynctask
	class DownloadFileAsync extends AsyncTask< String, String, String> {
		
		@Override
		protected void onPreExecute() {
		super.onPreExecute();
		showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
	/*
		@Override
		protected String doInBackground(String... aurl) {
			try {
				URL url = new URL(aurl[0]);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Downloader downloader = new Downloader();
			
			return null;
		}	
	*/	
	 
		@Override
		protected String doInBackground(String... aurl) {
		int count;
		try {
		URL url = new URL(aurl[0]);
		URLConnection conexion = url.openConnection();
		conexion.connect();
		int lenghtOfFile = conexion.getContentLength();
		Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
		InputStream input = new BufferedInputStream(url.openStream());
		OutputStream output = new FileOutputStream("/data/data/com.Ele_Demo.jackiez/databases/MyContacts.db");
		byte data[] = new byte[1024];
		long total = 0;
		while ((count = input.read(data)) != -1) {
		total += count;
		publishProgress(""+(int)((total*100)/lenghtOfFile));
		output.write(data, 0, count);
		}
		output.flush();
		output.close();
		input.close();
		} catch (Exception e) {
		Log.e("error",e.getMessage().toString());
		System.out.println(e.getMessage().toString());
		}
		return null;
		}
		
	
		protected void onProgressUpdate(String... progress) {
		Log.d("ANDRO_ASYNC",progress[0]);
		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		 
		@Override
		protected void onPostExecute(String unused) {
		dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
		}
    
}
